package com.zhaocheng.tank;

import java.awt.*;

/**
 * @author zhaocheng
 * @version 1.0
 * @date 2020/6/21 0021 10:24
 */
public class Bullet {

    public static final int WIDTH = ResourceManage.bulletD.getWidth();
    public static final int HIGHT = ResourceManage.bulletD.getHeight();
    private static final int SPEED = 10;

    private Group group = Group.GOOD;
    Rectangle rect = new Rectangle();

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    private int x, y;

    private Dir dir;

    private boolean living = true;

    TankFrame tf = null;

    public Bullet(int x, int y, Dir dir,TankFrame tf,Group group) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.tf = tf;
        this.group = group;

        rect.x = this.x;
        rect.y = this.y;
        rect.width = WIDTH;
        rect.height = HIGHT;
    }

    public void paint(Graphics g) {
        if (!living){
            tf.bullets.remove(this);
        }
        switch (dir){
            case RIGHT:
                g.drawImage(ResourceManage.bulletR,x,y,null);
                break;
            case UP:
                g.drawImage(ResourceManage.bulletU,x,y,null);
                break;
            case DOWN:
                g.drawImage(ResourceManage.bulletD,x,y,null);
                break;
            case LEFT:
                g.drawImage(ResourceManage.bulletL,x,y,null);
                break;
            default:
                break;
        }
        move();

    }

    private void move(){
        switch (dir){
            case DOWN:
                y += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            default:
                break;
        }
        if (x < 0 || y < 0||x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT){
            living = false;
        }
        rect.x = this.x;
        rect.y = this.y;
    }

    public void die(){
        this.living = false;
    }

    public void collidewith(Tank tank){
        if (tank.rect.intersects(rect) && this.group != tank.getGroup()){
            this.die();
            tank.die();
            int eX = tank.x + Tank.WIDHT / 2 - Explode.WIDTH / 2;
            int ey = tank.y + Tank.HIGHT / 2 - Explode.HIGHT / 2;
            tf.explodes.add(new Explode(eX,ey,tf));
        }

    }
}
